package com.enniswu.weitter.base;

import android.os.Bundle;
import android.support.annotation.LayoutRes;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import com.enniswu.weitter.R;

import butterknife.ButterKnife;
import butterknife.Unbinder;

public abstract class BaseFragment<P extends BaseContract.Presenter> extends Fragment implements BaseContract.View<P> {

    protected P presenter;
    private Unbinder unbinder;
    private TextView tvTitle;

    @Override
    public final View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view = inflater.inflate(setContentView(), container, false);
        tvTitle = view.findViewById(R.id.tv_title);
        unbinder = ButterKnife.bind(this, view);
        onCreateView(view);
        return view;
    }

    @Override
    public void onDestroyView() {
        if (presenter != null) {
            presenter.detachView();
            presenter = null;
        }
        unbinder.unbind();
        super.onDestroyView();
    }

    @LayoutRes
    protected abstract int setContentView();

    protected abstract void onCreateView(View contentView);

    protected void setTitle(String title) {
        if (tvTitle != null) {
            tvTitle.setText(title);
        }
    }

    public final void runOnUiThread(Runnable action) {
        if (getActivity() == null)
            return;
        getActivity().runOnUiThread(action);
    }

    @Override
    public void setPresenter(P presenter) {
        this.presenter = presenter;
    }

    @Override
    public void showMessage(String msg) {
        if (getActivity() != null) {
            ((BaseActivity) getActivity()).showMessage(msg);
        }
    }

    @Override
    public void showMessage(int resId) {
        if (getActivity() != null) {
            ((BaseActivity) getActivity()).showMessage(resId);
        }
    }

    @Override
    public boolean isShowLoading() {
        return getActivity() != null && ((BaseActivity) getActivity()).isShowLoading();
    }

    @Override
    public void showLoading() {
        if (getActivity() != null) {
            ((BaseActivity) getActivity()).showLoading();
        }
    }

    @Override
    public void dismissLoading() {
        if (getActivity() != null) {
            ((BaseActivity) getActivity()).dismissLoading();
        }
    }

    @Override
    public void showAlertLogin() {
        if (getActivity() != null) {
            ((BaseActivity) getActivity()).showAlertLogin();
        }
    }
}
